import axios from 'axios'
import { DOMAIN, PREFIX } from './config'
import { getAccessToken } from '@/utils/cache'
import { Notification } from 'element-ui'
/**
 * Create Axios
 */
export const http = axios.create({
  baseURL: DOMAIN + PREFIX
})

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */
http.defaults.headers.common = {
  'Accept': 'application/json',
  // 'X-CSRF-TOKEN': window.Laravel,
  'X-Requested-With': 'XMLHttpRequest'
}

http.interceptors.request.use((config) => {
  // if (!config.headers.Authorization) {
  //   const token = getAccessToken()
  //   if (token.trim()) {
  //     config.headers.Authorization = token
  //   }
  // }
  return config
})

/**
 * Handle all error messages.
 */
http.interceptors.response.use(function (response) {
  // console.log(response);
  return response
}, function (error) {
  // console.log(error)
  const { response } = error
  const { status, data } = response
  if (status === 401) {
    return Promise.reject(response)
  }
  if (status === 400 || status === 422) {
    if (data.data && JSON.stringify(data.data) !== '{}') {
      Object.values(data.data).forEach((item) => {
        Notification.error({
          title: '格式错误',
          message: item[0]
        })
      })
    } else {
      Notification.error({
        title: '格式错误',
        message: '请检查请求参数'
      })
    }
  }
  if (status === 403) {
    Notification.error({
      title: '权限不足',
      message: data.error_msg
    })
  }
  if (status === 404) {
    Notification.error({
      title: `404 ${data.error_msg}`,
      message: '页面不存在'
    })
  }
  if (status === 500) {
    Notification.error({
      title: '500 Internal Server Error',
      dangerouslyUseHTMLString: true,
      message: `<div style="width: 100%;word-wrap:break-word;word-break:break-all;">${data.error_msg}</div>`
    })
  }
  return Promise.reject(error)
})

export default http
